<template>
  <a-card :bordered="false">
    <h3>消息类型管理</h3>
    <MarketingFilter ref="filter" :type="3" @onAddMessageType="handleAddMessageType" @onSearch="onSearch"></MarketingFilter>
    <a-tabs v-model="activeKey" @change="tabChange">
      <a-tab-pane v-for="item in tabList" :tab="item.name" :key="item.status"> </a-tab-pane>
    </a-tabs>
    <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
      <span slot="image" slot-scope="record">
       <img class="img" :src="record.image" alt="">
      </span>
      <span slot="status" slot-scope="record">
        <span v-if="record.status == 0">启用</span>
        <span v-if="record.status == 1">禁用</span>
      </span>
      <span slot="action" slot-scope="record">
        <a @click="handleEditMessageType(record)">编辑</a>
        <a-divider type="vertical" />
        <a-popconfirm title="确认要删除该消息类型吗？"  ok-text="删除" cancel-text="取消" @confirm="handleAdvicesTypeDelete(record.id)">
          <a>删除</a>
        </a-popconfirm>
        <template v-if="record.status == 1">
          <a-divider type="vertical" />
          <a @click="handleChangeStatus(record.id,0)">启用</a>
        </template>
        <template v-if="record.status == 0">
          <a-divider type="vertical" />
          <a-popconfirm title="确认要禁用该消息类型吗？" ok-text="禁用" cancel-text="取消" @confirm="handleChangeStatus(record.id,1)">
            <a>禁用</a>
          </a-popconfirm>
        </template>
      </span>
    </s-table>
  </a-card>
</template>
<script>
import { advicesTypeList, advicesTypeEdit, advicesTypeDelete} from '@/api/micromall/communityMarketing'
import { STable } from '@/views/box/components'
import MarketingFilter from '../../components/MarketingFilter'

const columns = [
  {
    title: '消息类型名称',
    width: '120px',
    align: 'center',
    dataIndex: 'advicesName'
  },
  {
    title: 'icon图片',
    width: '200px',
    align: 'center',
    scopedSlots: { customRender: 'image' }
  },
  {
    title: '模板id',
    width: '180px',
    align: 'center',
    dataIndex: 'modelId'
  },
  {
    title: '创建方式',
    width: '280px',
    align: 'center',
    dataIndex: 'createWay'
  },
  {
    title: '状态',
    width: '120px',
    align: 'center',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '生效时间',
    width: '120px',
    align: 'center',
    dataIndex: 'updateTime'
  },
  {
    title: '操作',
    width: '150px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    MarketingFilter,
    STable
  },
  data() {
    return {
      tabList: [
        {
          name: '全部',
          status: ''
        },
        {
          name: '启用',
          status: '0'
        },
        {
          name: '禁用',
          status: '1'
        }
      ],
      activeKey: '1',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      columns,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {},

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (this.requestFlag()) return
        const data = {
          ...this.queryParam,
         current: parameter.pageNo,
          size: parameter.pageSize,
          status: this.activeKey
        }
        return advicesTypeList(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  created() {},
  computed: {},
  mounted() {},
  watch: {
    $route(to, from) {
      const whiteList = ['/micromall/community/marketingManagement/addOrEditMessageType/']
      const currentPathBase = '/micromall/community/marketingManagement/messageTypeList'
      const currentPath = this.$route.path
      if (this.checkRoute(from.path, whiteList) && to.path.includes(currentPathBase)) {
        this.$refs.table.refresh() // 刷新当前列表（记录上次页码）
      } else {
        if (currentPath.includes(currentPathBase)) {
          this.activeKey = ''
          this.tabChange(this.activeKey) // 刷新当前页面
        }
      }
    }
  },
  methods: {
    requestFlag() {
      const currentPathBase = '/micromall/community/marketingManagement/messageTypeList'
      const currentPath = this.$route.path
      if (!currentPath.includes(currentPathBase)) return true
      return false
    },

    // 新增消息类型
    handleAddMessageType(v) {
      this.$router.push(`/micromall/community/marketingManagement/addOrEditMessageType/${v}`)
    },

    // 替换特殊字符
    formatObj(values) {
      if (Object.prototype.toString.call(values) !== '[object Object]') {
        return values
      }
      let formValue = JSON.parse(JSON.stringify(values))
      Object.keys(formValue).forEach(i => {
        if ((typeof formValue[i]=='string')&&formValue[i].constructor==String) {
          formValue[i] = formValue[i].replace(/\%/g, "%25")
          formValue[i] = formValue[i].replace(/\#/g, "%23")
        } else if (Array.isArray(formValue[i])) {
          formValue[i] = formValue[i].map(e => {
           return (typeof e == 'object' && !Array.isArray(e)) ? this.formatObj(e) : e
          })
        }
      })
      return formValue
    },

     // 编辑消息类型
    handleEditMessageType(e) {
      const item = encodeURIComponent(JSON.stringify(this.formatObj(e)))
      this.$router.push(`/micromall/community/marketingManagement/addOrEditMessageType/${e.id}?item=${item}`)
    },

    // 禁用/启用
    handleChangeStatus(id,status) {
      // status 0:启用1:禁用
      const data = {
        id,
        status
      }
      advicesTypeEdit(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 删除
    handleAdvicesTypeDelete(id) {
      const data = {
        id
      }
      advicesTypeDelete(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 消息详情
    handleMessageDetails(v) {
      this.$router.push(`/micromall/community/marketingManagement/messageDetails/${v}`)
    },

    tabChange(activeKey) {
      this.$nextTick(() => {
        this.activeKey = activeKey
        this.$refs.filter.reset()
      })
    },

    checkRoute(fromPath, routeArr) {
      for (let i = 0; i < routeArr.length; i++) {
        if (fromPath.includes(routeArr[i])) {
          return true
        }
      }
      return false
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    },

    handleSubmitSort() {}
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img {
  display: block;
  margin: 0 auto;
  width: 60px;
  height: 60px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}

.remarks {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  word-break: break-all; /* 追加这一行代码 */
  /* autoprefixer: off */
  -webkit-box-orient: vertical;
  /* autoprefixer: on */
}
</style>
